package com.heima.comment.service.impl;

import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.uesr.UserFeign;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    GreenTextScan greenTextScan;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //1.检查参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (StringUtils.isBlank(dto.getContent()) || dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字");
        }
        //2.判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3查询用户
        ApUser apUser = userFeign.findUserById(user.getId().longValue());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        //安全过滤保存评论
        try {
            Map map = greenTextScan.greenTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            if ("pass".equals(suggestion)) {
                ApComment apComment = new ApComment();
                apComment.setAuthorId(apUser.getId());
                apComment.setAuthorName(apUser.getName());
                apComment.setImage(apUser.getImage());
                apComment.setContent(dto.getContent());
                apComment.setEntryId(dto.getArticleId());
                apComment.setCreatedTime(new Date());
                apComment.setUpdatedTime(new Date());
                apComment.setLikes(0);
                apComment.setReply(0);
                apComment.setType((short) 0);
                apComment.setFlag((short) 0);
                mongoTemplate.insert(apComment);
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "存在敏感词，请重新评论");
    }

    @Autowired
    CommentHotService commentHotService;

    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //检查参数
        if (dto == null || dto.getCommentId() == null || (dto.getOperation() > 1 && dto.getOperation() < 0)) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3查询用户
        ApUser apUser = userFeign.findUserById(user.getId().longValue());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        //查询评论
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "评论已经被删除");
        }
        // 用户不能重复点赞
        ApCommentLike apCommentLike = mongoTemplate.findOne(
                Query.query(Criteria.where("authorId").is(user.getId())
                        .and("commentId").is(dto.getCommentId())),
                ApCommentLike.class);
        if (apCommentLike != null && apCommentLike.getOperation() == 0 && dto.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已点赞，无需重复点赞");
        }
        //点赞
        if (dto.getOperation() == 0) {
            // 点赞+1
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);
            //点赞大于五并且是普通评论则升级为热点评论
            if (apComment.getLikes() >= 5 && apComment.getFlag().shortValue() == 0) {
                //计算热点评论评论
                commentHotService.hotCommentExecutor(apComment.getEntryId(), apComment);
            }
            // 保存点赞评论信息
            apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentLike);
        } else {
            //取消点赞
            apComment.setLikes(apComment.getLikes() <= 0 ? 0 : apComment.getLikes() - 1);
            mongoTemplate.save(apComment);
            mongoTemplate.remove(
                    Query.query(Criteria.where("authorId").is(user.getId())
                            .and("commentId").is(dto.getCommentId())),
                    ApCommentLike.class);
            ;
        }
        //返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("likes", apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //检查参数
        if (dto == null || dto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        //初始化评论列表
        List<ApComment> apCommentList = null;
        //首页
        if (dto.getIndex() == 1) {
            //查询热点评论
            Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId())
                    .and("flag").is(1))
                    .with(Sort.by(Sort.Direction.DESC, "likes"));
            apCommentList = mongoTemplate.find(query, ApComment.class);
            //查询普通评论
            if (apCommentList != null && apCommentList.size() != 0) {
                 size=size-apCommentList.size();
                 //首页
                Query query1 = Query.query(Criteria.where("entryId").is(dto.getArticleId())
                        .and("flag").is(0).and("createdTime").lt(dto.getMinDate())).limit(size)
                        .with(Sort.by(Sort.Direction.DESC, "createdTime"));
                List<ApComment> apCommentList1 = mongoTemplate.find(query1, ApComment.class);
                apCommentList.addAll(apCommentList1);
            }else {
                Query query2 = Query.query(Criteria.where("entryId").is(dto.getArticleId())
                        .and("flag").is(0).and("createdTime")
                        .lt(dto.getMinDate())).limit(size)
                        .with(Sort.by(Sort.Direction.DESC, "createdTime"));
                apCommentList = mongoTemplate.find(query2, ApComment.class);
            }
        }else {
            Query query3 = Query.query(Criteria.where("entryId")
                    .is(dto.getArticleId()).and("flag").is(0).and("createdTime")
                    .lt(dto.getMinDate())).limit(size)
                    .with(Sort.by(Sort.Direction.DESC, "createdTime"));
            apCommentList = mongoTemplate.find(query3, ApComment.class);
        }
//        //查询Mongo文章所有评论列表
//        List<ApComment> apCommentList = mongoTemplate.find(Query.query(Criteria.where("entryId").is(dto.getArticleId())
//                .and("createdTime").is(dto.getMinDate()))
//                .limit(dto.getSize())
//                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApComment.class);

        //封装查询结果
        //用户未登录 直接返回评论列表
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apCommentList);
        }
        //用户登录则要加载点赞过的评论
        //获取评论的id集合
        List<String> idList = apCommentList.stream().map(comment -> comment.getId()).collect(Collectors.toList());
        // 查询 点赞批量列表 按照评论id 筛选
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(
                Query.query(Criteria.where("commentId").in(idList)
                        .and("authorId").is(user.getId()))
                , ApCommentLike.class);
        //获取封装ApCommentVo集合
        List<ApCommentVo> apCommentVoList = new ArrayList<>();
        // 遍历当前用户点赞列表 和当前评论列表
        if (apCommentList != null && apCommentList.size() > 0 && apCommentLikes != null && apCommentLikes.size() > 0) {
            apCommentList.forEach(comment -> {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(comment, apCommentVo);
                apCommentLikes.forEach(apCommentLike -> {
                    if (comment.getId().equals(apCommentLike.getCommentId())) {
                        apCommentVo.setOperation((short) 0);
                    }
                });
                apCommentVoList.add(apCommentVo);
            });
            return ResponseResult.okResult(apCommentVoList);
        }
        //当前文章为被评论返回空集合
        return ResponseResult.okResult(apCommentList);
    }
}
